<!--  -->
<template>
  <div>
    <div>
      <!--连线题-->
      <template>
        <div
          id="draw"
          class="draw-container"
          ref="mapping"
          @mousemove="rootMousemoveHandler"
          @mouseup="rootMouseupHandler"
        >
          <ul class="question-left">
            <li
              class="cursor question-left-item"
              v-for="(item, i) in questionLeft"
              :key="i"
              :data-index="i"
              @mousedown="questionLeftMousedownHandler"
            >{{ item.questionItem }}</li>
          </ul>
          <ul class="question-right">
            <li
              class="cursor question-right-item"
              v-for="(item, i) in questionRight"
              :key="i"
              :data-index="i"
              @mouseup="questionRightMouseupHandler"
            >{{ item.questionItem }}</li>
          </ul>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { SVG } from "@svgdotjs/svg.js";
export default {
  name: "",
  props: [""],
  data() {
    return {
      questionLeft: [
        {
          id: 0,
          questionItem: "测试一"
        },
        {
          id: 1,
          questionItem: "测试二"
        }
      ],
      questionRight: [
        {
          id: 0,
          questionItem: "测试一"
        },
        {
          id: 1,
          questionItem: "测试二"
        }
      ],
      svg: {
        draw: null,
        lineArr: [],
        currentInfo: {}
      }
    };
  },
  components: {},
  computed: {},
  beforeMount() {},
  methods: {
    initSvg() {
      this.$nextTick(() => {
        if (!this.svg.draw) {
          this.svg.draw = SVG()
            .addTo("#draw")
            .size("100%", "100%");
          this.svg.draw.addClass("draw");
        }
        this.createQuestionLine();
        //获取题目的高度
        this.$nextTick(() => {
          let qusetionWrapH = document.querySelector(".question-left")
            .offsetHeight;
          this.$refs.mapping &&
            (this.$refs.mapping.style.height = qusetionWrapH + "px");
        });
      });
    },
    /*绑定根元素mousemove事件*/
    rootMousemoveHandler(e) {
      e.preventDefault();
      let { currentInfo } = this.svg,
        parentPosition = document.querySelector(".draw-container"),
        scrrllTop =
          document.documentElement.scrollTop || document.body.scrollTop;
      if (Object.keys(currentInfo).length != 0 && currentInfo.isDraw) {
        let end = {};
        end.x = e.pageX - parentPosition.getBoundingClientRect().left;
        end.y =
          e.pageY - (parentPosition.getBoundingClientRect().top + scrrllTop);
        currentInfo.line.plot(
          currentInfo.begin.x,
          currentInfo.begin.y,
          end.x,
          end.y
        );
      }
    },
    /*绑定根元素mouseup事件*/
    rootMouseupHandler(e) {
      let target = e.target.className,
        { currentInfo } = this.svg;
      if (
        !(target.includes && target.includes("question-right-item")) &&
        currentInfo.line
      ) {
        currentInfo.line.hide();
        currentInfo.isDraw = false;
      }
    },
    /*绑定答案的mousedown事件*/
    questionLeftMousedownHandler(e) {
      let target = e.target;
      let index = target.getAttribute("data-index");
      console.log(this.questionLeft[index].id);
      let curLine = this.svg.lineArr.filter(
        e => e.beginValueId == this.questionLeft[index].id
      )[0];
      //如果存在结果则删除
      if (curLine.endValue) {
        curLine.line.hide();
        curLine.endValue = "";
        curLine.beginElement && curLine.beginElement.classList.remove("active");
        curLine.endElement && curLine.endElement.classList.remove("active");
      } else {
        curLine.beginElement = target;
        curLine.begin.y = target.offsetTop + target.offsetHeight / 2;
        curLine.begin.x = target.offsetLeft + target.offsetWidth;
        curLine.line.show();
        curLine.line.stroke({
          color: "#000000"
        });
        curLine.line.plot(
          curLine.begin.x,
          curLine.begin.y,
          curLine.begin.x,
          curLine.begin.y
        );
        this.svg.currentInfo.isDraw = true;
        this.svg.currentInfo = curLine;
      }
      // 获取正确答案
      this.getMappingAnswer();
    },
    /*绑定答案的mouseup事件连线*/
    questionRightMouseupHandler(e) {
      if (
        Object.keys(this.svg.currentInfo).length == 0 ||
        !this.svg.currentInfo.isDraw
      ) {
        return;
      }

      let target = e.target;
      let index = target.getAttribute("data-index");
      let questionItem = this.questionRight[index].questionItem;
      let curLine = this.svg.lineArr.filter(
        e => e.beginValueId == this.svg.currentInfo.beginValueId
      )[0];

      for (let item of this.svg.lineArr) {
        // 判断右侧选项是否已经被连接
        if (item.endValue === questionItem) {
          curLine.line.hide();
          return;
        }
      }

      curLine.end.y = target.offsetTop + target.offsetHeight / 2;
      //为什么要用target.parentElement.offsetLeft请看页面布局。
      curLine.end.x = target.parentElement.offsetLeft;
      curLine.endElement = target;
      curLine.endValue = questionItem;
      curLine.line.plot(
        curLine.begin.x,
        curLine.begin.y,
        curLine.end.x,
        curLine.end.y
      );
      // curLine.endValue = '';
      //添加连接成功后的class
      if (this.svg.currentInfo.beginValue && this.svg.currentInfo.endValue) {
        curLine.beginElement.classList.add("active");
        curLine.endElement.classList.add("active");
        // 获取正确答案
        this.getMappingAnswer();
      }
      this.svg.currentInfo = {};
    },
    drawCircle(id) {
      this.charts = echarts.init(document.getElementById(id));
      this.charts.setOption({
        title: {
          text: "基础雷达图"
        },
        legend: {
          data: ["预算分配（Allocated Budget）", "实际开销（Actual Spending）"]
        },
        radar: {
          // shape: 'circle',
          indicator: this.indicator
        },
        series: [
          {
            name: "预算 vs 开销（Budget vs spending）",
            type: "radar",
            data: [
              {
                value: [4200, 3000, 20000, 35000, 50000, 18000],
                name: "预算分配（Allocated Budget）"
              },
              {
                value: [5000, 14000, 28000, 26000, 42000, 21000],
                name: "实际开销（Actual Spending）"
              }
            ]
          }
        ]
      });
    },
    createSvgline() {
      let { draw } = this.svg;
      let line = draw.line();
      line.stroke({
        color: "#000000",
        width: 2,
        opacity: 0.6,
        linecap: "round"
      });
      line.click(function() {
        console.log("line click");
      });
      line.hide();
      return line;
    },
    createQuestionLine() {
      let { lineArr, draw, currentInfo } = this.svg;
      console.log("createQuestionLine:", this.questionLeft);
      this.questionLeft.forEach(e => {
        let obj = {};
        if (typeof e.answerRightIndex == "number") {
          // 回显答案
          let questionLeftItem = document.querySelector(
            `.question-left-item[data-index="${e.index}"]`
          );
          let questionRightItem = document.querySelector(
            `.question-right-item[data-index="${e.answerRightIndex}"]`
          );
          let beginX =
            questionLeftItem.offsetLeft + questionLeftItem.offsetWidth;
          let beginY =
            questionLeftItem.offsetTop + questionLeftItem.offsetHeight / 2;
          let endX = document.querySelector(".question-right").offsetLeft;
          let endY =
            questionRightItem.offsetTop + questionLeftItem.offsetHeight / 2;
          obj.end = {
            x: endX,
            y: endY
          };
          obj.begin = {
            x: beginX,
            y: beginY
          };
          obj.isDraw = true;
          obj.beginValue = e.questionItem;
          obj.beginValueId = e.id;
          obj.endValue = this.questionRight[e.answerRightIndex].questionItem;
          obj.line = this.createSvgline();
          lineArr.push(obj);
          obj.line.plot(obj.begin.x, obj.begin.y, obj.end.x, obj.end.y);
          obj.line.show();
        } else {
          obj.end = {};
          obj.begin = {};
          obj.isDraw = true;
          obj.beginValue = e.questionItem;
          obj.beginValueId = e.id;
          obj.line = this.createSvgline();
          lineArr.push(obj);
        }
      });
    },
    /*获取练习题答案  主要获取事件在questionRightMouseupHandler和questionLeftMousedownHandler中获取*/
    getMappingAnswer() {
      let userAnswerVal = (() => {
        let userAnswer = [];
        for (let item of this.svg.lineArr) {
          if (item.endValue) {
            userAnswer.push({
              answerLeft: item.beginValue,
              answerRight: item.endValue
            });
          } else {
            userAnswer.push({
              answerLeft: "",
              answerRight: ""
            });
          }
        }
        return userAnswer;
      })();

      this.data.userAnswer = [
        {
          correctAnswer: JSON.stringify(userAnswerVal),
          questionCorrectAnswer: this.data.tqaExamUnifiedExamQuestionList[0]
            .correctAnswer,
          questionId: this.data.tqaExamUnifiedExamQuestionList[0].id,
          questionIndex: this.data.tqaExamUnifiedExamQuestionList[0]
            .questionIndex,
          questionType: this.data.questionType,
          unifiedExamId: this.id,
          unifiedExamSubjectQuestionGroupId: this.data
            .tqaExamSubjectQuestionGroupId
        }
      ];
    }
  },
  //调用
  mounted() {
    this.initSvg();
  },
  watch: {}
};
</script>

<style lang='css' scoped>
.gestalt {
  display: flex;
  flex-direction: column;
}
.radio-group {
  display: flex;
}
.draw-container {
  width: 620px;
  height: 200px;
  position: relative;
}
.question-topic {
  display: flex;
}
.question-index {
  width: 30px;
  height: 24px;
  line-height: 24px;
  font-size: 14px;
  margin-right: 10px;
  text-align: center;
  border-radius: 3px;
  background: #00adef;
  color: #fff;
}
.question-title {
  color: #000;
  font-size: 18px;
  line-height: 24px;
  font-weight: bold;
}
.question-left,
.question-right {
  position: absolute;
}
.question-left-item,
.question-right-item {
  width: 220px;
  height: 32px;
  line-height: 30px;
  background: #ecf5ff;
  border: 1px solid #b3d8ff;
  border-radius: 10px;
  font-size: 16px;
  text-align: center;
  margin: 20px 0 20px;
  color: #409eff;
}
.hover {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.question-right {
  right: 0;
}
.question-desc {
  margin: 30px 0;
  font-size: 18px;
  color: #000000;
}
.question-desc {
  margin-bottom: 30px;
}
</style>